package easyto.predicate;


import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 开头任意取名，但是必须以RoutePredicateFactory后缀结尾 <br/>
 *
 * yaml配置断言：
 * predicates:
 *      - Path=/click-ppc/**  # 断言，路径相匹配的进行路由
 *      - Custom=gold
 * Custom指定CustomRoutePredicateFactory断言工厂
 * gold则是指定{@link Config}中userLevel的值。
 * 表示请求路径中包含userLevel参数并且值为指定的gold时，断言通过。否则会报错404
 * http://localhost:9090/click-ppc/test/11/chain/2222/details?userLevel=gold&youxiao=statssss
 * @Description 自定义predicates断言
 */
@Component
public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {


    public CustomRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userLevel");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return serverWebExchange -> {
            String userLevel = serverWebExchange.getRequest().getQueryParams().getFirst("userLevel");
            if (userLevel == null) {
                return false;
            }
            return userLevel.equalsIgnoreCase(config.getUserLevel());
        };
    }

    @Getter
    @Setter
    @Validated
    public static class Config {
        private String userLevel;
    }

}

